import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import request from 'superagent';
import {  message,Table,Dropdown,Menu,Button,Input ,Row,Col,Select,Popconfirm,Modal,Form, Radio,Upload,Icon} from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import api from '../api';
import moment from 'moment';
import {bind_change} from '../common/State';

import {SMS_TYPE} from '../constants/index';


export default class Sms extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           page:1,
           total:1,
           pageSize:10,
           list:[],
           search:{},
           loading:true,
           visible:false
        };
    }

    componentWillMount(){
        this.doFetch();
    }
    componentWillReceiveProps(nextProps){
        
    }
    async doFetch(page=1){
      let {search} = this.state;

      let result = await api('/operation/sms/list',{...search,page});

      if(result.cd!=0){
        message.error(result.msg);
        this.setState({loading:false})
        return;
      }
      this.setState({
          page,
          total:result.total,
          list:result.data,
          loading:false
      })
    }

    //手工确认
    async handleConfirm(record){
        let result = await api('/operation/sms/confirm',{id:record.id});
        if(result.cd!=0){
          message.error(result.msg);
          return
        }
        message.success('操作成功',1,() =>{
          let {page} = this.state;
          this.doFetch(page);
        })
    }


    //分页
    toPage({current:page,pageSize,total}){
      this.setState({loading:true})
      this.doFetch(page);
    }

   
    render() {
        var {list, page,total,pageSize,loading,visible}=this.state;
        return (
            <div >
                <NavBar navs={[{title:'短信管理'}]} />
                <ContentBody className='container'>
                  <div className='marginB10'>
                      <Button 
                        type="primary" 
                        onClick={()=>{
                          this.setState({visible:true})
                        }}
                      >
                        发送短信
                      </Button>
                  </div>  

                  <Table 
                    bordered
                    columns={this.getColumns()} 
                    simple 
                    dataSource={list}
                    pagination={{
                      current:page,
                      total,
                      pageSize,
                      showQuickJumper : true
                    }}
                    loading={loading}
                    onChange={this.toPage.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={record => record.id}
                  />
                </ContentBody>
                <SmsModalForm 
                    visible = {visible}
                    onCancel = {() => {
                      this.setState({visible:false})
                    }}
                    onOk = {() => {
                      let {page} = this.state;
                      this.setState({
                        loading:true,
                        visible:false
                      })
                      this.doFetch(page);

                    }}
                />
            </div>
        );
    }

    getColumns(){

      let columns = [
            {
              title: '短信记录ID',
              dataIndex: 'id',
              key: 'id',
            }, {
              title: '发送目标',
              dataIndex: 'receiverStr',
              key: 'receiverStr'
            }, {
              title: '发送人数',
              dataIndex: 'number',
              key: 'number'
            },{
              title: '短信内容',
              dataIndex: 'content',
              key: 'content'
            },{
              title: '创建时间',
              dataIndex: 'create_at',
              key: 'create_at'
            },{
              title: '系统完成时间',
              dataIndex: 'complete_at',
              key: 'complete_at'
            },{
              title: '短信状态',
              dataIndex: 'status',
              key: 'status',
              render:(status)=>{
                return status==1?'已完成':status==0?'未完成':'未知'
              }
            },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:100,
              render: (record) =>{
                if(record.status==0){
                  return (
                      <span>
                        <Popconfirm 
                          title="确定要手工确认?" 
                          onConfirm={this.handleConfirm.bind(this,record)} 
                          okText="确定" 
                          cancelText="取消"
                        >
                          <a href='javascript:void 0'>手工确认</a>
                        </Popconfirm>
                      </span>
                    )
                }
                  
              } ,
            }
        ];

        return columns
    }
}

class SmsModal extends React.Component {

    constructor(props,context){
      super(props,context);
      this.state = {
        confirmLoading:false,
        mode:'write'
      }
    }

    handleOk () {
      const {validateFieldsAndScroll,setFields } = this.props.form;
      let {mode} = this.state;
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          return
        }
        if(mode=='write'&&!/^(1\d{10},)*(1\d{10})$/g.test(values.receiverStr)){
          setFields({
            receiverStr:{
              value:values.receiverStr,
              errors:[new Error('请输入正确手机号格式（多个以逗号分隔）')]
            }
          })
          return;
        }
        this.send(values);
      })
    }
    async send(values){
      let {mode,receiverStr} = this.state;
      let {onOk} = this.props;
      if(mode=='upload'){
        values.receiverStr = receiverStr
        delete values.receiverStr_upload;
      }
      if(mode=='all'){
        values.receiverStr = 'all'
      }
      let result = await api('/operation/sms/send',{...values});
      if(result.cd!=0){
        message.error(result.msg);
        return;
      }
      message.success('发送成功',1,()=>{
        onOk()
      })
    }

    //上传
    onDrop =  (e,z) => {
      var file = e.file;
      message.loading("正在上传...",0);
      var req = request.post('/file/parse-execl');
      req.attach(file.name, file);
      req.end((err,rsq)=>{
        message.destroy();
          if(err){
              message.error("解析失败");
          } else {
              if(err){
                  message.error(this,"解析失败");
              }else{
                message.success('解析成功')
                if(rsq.text){
                  this.setState({
                    fileName:file.name,
                    receiverStr:JSON.parse(rsq.text).join(',')
                  })
                }
                  
              }
          }
      });
    }
    
    render (){
      let {visible,onCancel,onOk} = this.props;
      let {getFieldDecorator} = this.props.form;
      let {confirmLoading,mode,fileName} =  this.state;
      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 14 },
        },
      };
      return (
        <Modal title="发送短信"
          visible={visible}
          onOk={this.handleOk.bind(this)}
          confirmLoading={confirmLoading}
          onCancel={onCancel}
          okText='发送'
        >
        <div className="text-center">
          <Radio.Group 
            onChange={(e) => {
              this.setState({mode:e.target.value})
            }} 
            value={mode} 
            style={{ marginBottom: 8 }}>
            <Radio.Button value="write">指定用户</Radio.Button>
            <Radio.Button value="all">全部用户</Radio.Button>
            <Radio.Button value="upload">上传用户</Radio.Button>
          </Radio.Group>
        </div>
        <div className="height20"></div>
        <Form style={{width:'100%',margin:'auto'}}>
          <Row>
            <Col span={24}>
              {mode=='write'?
                <Form.Item 
                  {...formItemLayout}
                  label="手机号码"
                >
                  {getFieldDecorator('receiverStr', {
                    rules: [
                      {
                        required: true,
                        message: '请输入手机号码(以逗号分隔)',
                      }
                    ]
                  })(<Input.TextArea
                        rows={2}
                        placeholder="请输入手机号码(以逗号分隔)"
                      />
                  )}
                </Form.Item>
                :mode=='upload'?
                <Form.Item 
                  {...formItemLayout}
                  label="手机号码"
                >
                  {getFieldDecorator('receiverStr_upload', {
                    rules: [
                      {
                        required: true,
                        message: '请上传手机号码',
                      }
                    ]
                  })(
                    <Upload 
                      customRequest={this.onDrop.bind(this)} 
                      showUploadList={false}
                      beforeUpload = {(file,fileList) =>{
                        if(fileList.length>1){
                          return false
                        }
                      }}
                    >
                      <Button>
                        <Icon type="upload" /> {fileName?fileName:'上传手机号'}
                      </Button>
                    </Upload>
                  )}
                </Form.Item>
                :""
              }
              
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item 
                label="发送内容"
                {...formItemLayout}
              >
                {getFieldDecorator('content', {
                  rules: [
                    {
                      required: true,
                      message: '请输入发送内容',
                    },
                  ]
                })(<Input.TextArea
                      rows={4}
                      placeholder="请输入发送内容"
                    />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item 
                label="短信类型"
                {...formItemLayout}
              >
                {getFieldDecorator('type', {
                  rules: [
                    {
                      required: true,
                      message: '请选择短信类型',
                    },
                  ],
                  initialValue:""
                })(
                  <Select
                  style={{width:"100%"}}
                  >
                    <Option value="">请选择</Option>
                    {
                      Object.keys(SMS_TYPE).map((key,index) => {
                        return (
                          <Option key={index} value={key}>{SMS_TYPE[key]}</Option>
                        )
                      })
                    }
                  </Select>
                )}
              </Form.Item>
            </Col>
          </Row>
        </Form>
        </Modal>
      )
    }
}
var SmsModalForm = Form.create()(SmsModal);
Sms.contextTypes= { router: React.PropTypes.object.isRequired};

